package com.zjl.legendary.service.impl;

import com.zjl.legendary.dao.UserTaskDao;
import com.zjl.legendary.entity.UserTask;
import com.zjl.legendary.service.intf.UserTaskService;
import com.zjl.legendary.util.DateUtils;
import com.zjl.legendary.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author zhoujingluo
 * @date 2021/5/29 21:30
 */
@Service
@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.SUPPORTS,
        readOnly = true,rollbackFor = Exception.class)
public class UserTaskServiceImpl implements UserTaskService {
    @Autowired
    private UserTaskDao userTaskDao;

    /**
     * 查询用户任务列表
     * @param uid 用户id
     * @return 返回用户任务列表
     */
    @Override
    public List<UserTask> query(Integer uid) {
        return userTaskDao.selectByUid(uid);
    }

    /**
     * 新增用户任务
     * @param task 用户提交的任务信息
     * @return 执行结果 true-执行成功 false-执行失败
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public boolean addTask(UserTask task) {
        if (task != null){
            if (StrUtils.isNotNull(task.getTitle())){
                userTaskDao.insertTask(task);
                List<UserTask> userTasks = userTaskDao.selectByUid(task.getUid());
                if (userTasks != null){
                    task.setId(userTasks.get(0).getId());
                    task.setCtime(userTasks.get(0).getCtime());
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public UserTask queryById(Integer id) {
        List<UserTask> tasks = userTaskDao.selectById(id);
        if (tasks.size() > 0){
            return tasks.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<UserTask> query(Integer uid, Date date) {
        String dateStr = DateUtils.utilToStr(date);

        return userTaskDao.selectToday(uid,dateStr);
    }
}
